<?php
namespace Admin\Controller;

class AdController extends Controller {

    public function index() {
        $m    = D('Ad');
        $page = $m->where($this->indexExpr)->order($this->sortExpr)->page2();

        $this->assign('page', $page);
		$this->display();
    }

    public function  add() {
        $planId = I('get.plan_id', 0, 'intval');

        if (empty($planId)) {
            throw new \Exception('没有计划编号，无法增加广告');
        }

        if (!$planRecord = D('Plan')->getById($planId)) {
            throw new \Exception('没有找到计划信息');
        }

        $record = [            
            'plan_id'   => $planRecord['id'],
            'plan_type' => $planRecord['type'],
            'plan_name' => $planRecord['name'],
        ];

        $this->assign('record', $record)
             ->display();
    }

    public function modify() {
        $id = I('get.id', 0, 'intval');

        if (empty($id)) {
            throw new \Exception('参数不完整，无法获取数据');
        }

        $m = D('Ad');

        if (!$record = $m->getById($id)) {
            throw new \Exception('没有找到广告信息');
        }

        if (!$planRecord = D('Plan')->getById($record['plan_id'])) {
            throw new \Exception("没有找到广告计划数据");
        }

        if ($record['type'] == 'zl' && $tmp = $m->parseZlCode($record['code'])) {
            $record = array_merge($record, $tmp);
        }

        $record['plan_name'] = $planRecord['name'];
        $record['plan_type'] = $planRecord['type'];

        $this->assign([            
            'record' => $record
        ])->display();
    }

    public function doSave() {
        $d = $_POST;
        $m = D('Ad');

        try {
            $r = $m->save2($d) 
                 ? ['s' => true,  'm' => '保存成功']
                 : ['s' => false, 'm' => '保存出错'];
        } catch (\Exception $e) {
            $r = ['s' => false, 'm' => $e->getMessage()];
        }

        showJson($r);
    }

    public function del() {
        $id = I('id', 0);

        if(empty($id)) {
            showJson(array('s' => false, 'm' => '参数不完整，无法删除数据'));
        }

        $r = D2()->del2($id) 
             ? array('s' => true, 'm' => '删除成功') 
             : array('s' => false, 'm' => '删除出错');

        showJson($r);
    }

    /**
     * show
     * 显示广告
     *
     * @return void
     */
    public function show() {
        $id = empty($_GET['id']) ? 0 : (int)$_GET['id'];

        if(empty($id)) {
            throw new \Exception('参数不完整，无法显示广告');
        }

        $m = D2();

        if(!$rAd = $m->getByAdId($id)) {
            throw new \Exception('没有找到广告信息');
        }

        $html = $m->getOutHtml($rAd['type'], $rAd['url'], $rAd['width'], $rAd['height'], $rAd['code']);

        exit($html);
    }

    public function changeStatus() {
        $id     = I('id', 0);
        $status = I('status', 0);

        try {
            $r = D('Ad')->changeStatus($id, $status)
                 ? ['s' => true,  'm' => '操作成功']
                 : ['s' => false, 'm' => '操作出错'];
        } catch(\Exception $e) {
            $r = ['s' => false, 'm' => $e->getMessage()];
        }

        showJson($r);
    }

    /**
     * add2
     * 批量上传广告
     *
     * @return void
     */
    public function add2() {
        if(!C('C_IS_MASTER_SERVER')) {
            throw new \Exception('批量上传广告的操作只能在主服务器上进行');
        }

        $planId = I('get.id', 0, 'intval');

        if(empty($planId)) {
            throw new \Exception('参数不完整，无法获取数据');
        }

        if(!$rPlan = D2('Plan')->getByPlanid($planId)) {
            throw new \Exception('没有找到广告计划');
        }

        if($rPlan['plantype'] != 'cpc') {
            throw new \Exception('只有CPC计划才能批量上传广告');
        }

        if (!$planDeviceRecords = D2('PlanDevice')->where(array('plan_id' => $planId))->select()) {
            throw new \Exception('没有找到计划投放设备数据');
        }

        $this->assign(array(
            'plan'         => $rPlan,
            'plan_devices' => $planDeviceRecords,
        ))->display();
    }

    public function doAdd2(){
        $dao = array_merge(I('post.'), $_FILES);
        $m   = D2();

        try {
            $m->addFromZip($dao);
            $r = array('s' => 1, 'm' => '批量上传广告成功');
        } catch(Exception $e) {
            $r = array('s' => 0, 'm' => $e->getMessage());
        }

        echo <<<EOD
<script>
alert('{$r['m']}');

if({$r['s']}) {
    top.window.location.href=top.window.location.href;
}
</script>
EOD;
        showJson($r);
    }

    /**
     * copy2
     * 复制广告代码
     *
     * @return void
     */
    public function copy2() {
        $mPlan = D2('Plan');

        if(!$rPlan = $mPlan->where(array('plantype' => 'cpc'))->order('planid DESC')->select()) {
            throw new \Exception('没有找到CPC计划，无法复制广告');
        }

        $this->assign('plan', $rPlan)->display();
    }

    /**
     * doCopy2
     * 执行复制广告代码
     *
     * @return void
     */
    public function doCopy2() {
        $d = I('post.');
        $m = D2();

        try {
            $m->copy2($d);
            $r = array('s' => true, 'm' => '广告复制成功');
        } catch(Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * getByPlanId
     * 根据计划编号获取所有广告
     *
     * @return void
     */
    public function getByPlanId() {
        $planId = I('get.id', 0, 'intval');

        if(empty($planId)) {
            showJson(array('s' => false, 'm' => '参数不完整，无法获取广告数据'));
        }

        $expr = array('plan_id' => $planId);
        $sort = 'type DESC, width ASC, height ASC';
        $r    = ($record = D2()->where($expr)->order($sort)->select())
                ? array('s' => true,  'd' => $record)
                : array('s' => false, 'm' => '没有找到广告数据');

        showJson($r);
    }

    /**
     * move2
     * 移动广告代码
     *
     * @return void
     */
    public function move2() {
        $mPlan = D2('Plan');

        if(!$rPlan = $mPlan->where(array('plantype' => 'cpc'))->order('planid DESC')->select()) {
            throw new \Exception('没有找到CPC计划，无法复制广告');
        }

        $this->assign('plan', $rPlan)->display();
    }

    /**
     * doMove2
     * 移动广告
     *
     * @return void
     */
    public function doMove2() {
        $d = I('post.');
        $m = D2();

        try {
            $m->move2($d);
            $r = array('s' => true, 'm' => '广告移动成功');
        } catch(Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * tmpUpgradeForUrl
     * 升级针对不同终端对应的网址字段
     *
     * @return void
     */
    public function tmpUpgradeForUrl() {
        $offset = 0;
        $limit  = 500;
        $_limit = "{$offset},{$limit}";

        $m = D2('Ad');
        $planDeviceModel = D2('PlanDevice');

        while ($records = $m->order('ad_id DESC')->limit($_limit)->select()) {
            foreach ($records as $_ad) {
                $_planId = $_ad['plan_id'];

                if (!$_planDeviceRecords = $planDeviceModel->where(array('plan_id' => $_planId))->select()) {
                    continue;
                }

                $_dao = array(
                    'ad_id' => $_ad['ad_id'],
                );

                foreach ($_planDeviceRecords as $_planDeviceRecord) {
                    $_urlKey = 'url_' . $_planDeviceRecord['pd_device'];
                    $_dao[$_urlKey] = $_planDeviceRecord['pd_url'];
                }

                if (!$m->save($_dao)) {
                    exit("{$_ad['ad_id']} error");
                }
            }

            $offset += $limit;
            $_limit = "{$offset},{$limit}";
        }

        echo 'Finish';
    }

}
